import { getCamelCase, messages } from "share/common";
import React, { Component } from 'react'
import { connect } from "react-redux"
import { Tabs, Modal, message } from "antd";
import TemplateContent from "containers/finance-setting/loan-setting/template-content";
import SlideFrame from 'components/slide-frame';
import RepaymentDetailFrame from 'containers/loan-billing/template/refund-content'
import openSlideFrame from 'share/openSlideFrame';
import ViewHistory from "containers/loan-billing/template/view-history"
import Template from "components/UI/template"
import TransactionModal from "../../loan-billing/template/transaction-modal"
import repaymentContent from "../../loan-billing/template/repayment-content"
import ListSelector from "components/list-selector"
import loanAndRefundService from "./loan-and-refund.service"

const { Header, Middle } = Template;

@connect(mapStateToProps)
class LoanRefund extends Component {

  state = {
    nowStatus: 'loanGlobalView',
    historyModal: false,
    historyId: '',
    editRecord: {}
  };

  onChangeTabs = key => {
    this.setState({ nowStatus: key })
  };

  handleViewHistory = (e, record) => {
    e.stopPropagation();
    this.setState({ historyId: record.id }, () => this.setState({ historyModal: true }));
  };

  handleViewRefund = item => {
    this.setState({ historyModal: false }, () => {
      if (item.type === '2' || item.type === '3') {
        openSlideFrame.openExpenseReport({
          expenseReportOID: item.expenseReportOid,
          entry: 'view'
        }, {}, this);
      } else {
        this.setState({ historyModal: false }, () => {
          SlideFrame.open({
            content: RepaymentDetailFrame,
            params: {
              refundParams: item.repaymentOid,
              pathname: this.props.location.pathname
            },
            title: messages('finance-1.key469')/*还款单详情*/,
            afterClose: value => value && this.content.tableRef.getList()
          }, this);
        });
      }
    });
  };

  refund = record => {
    if (record.expenseReportOid) {
      openSlideFrame.openExpenseReport({
        expenseReportOID: record.expenseReportOid,
        entry: 'view'
      }, {}, this);
    } else {
      SlideFrame.open({
        content: RepaymentDetailFrame,
        params: {
          refundParams: record.repaymentOid,
          pathname: this.props.location.pathname
        },
        title: messages('finance-1.key469')/*还款单详情*/,
        afterClose: value => value && this.content.tableRef.getList()
      }, this);
    }
  };

  operate = {
    repaymentSlipManagement: {
      title: messages('common.operation')/*操作*/, dataIndex: 'operate',
      render: (value, record) => (
        <a
          onClick={() => this.refund(record)}
          disabled={record.status === 1001 && this.props.currentPageRoute.subFunctions.find(item =>
            item.key === 'repayment-slip-management').operationType === 'R'}>
          { (record.status === 1001 && !record.expenseReportOid) ? messages('finance-1.key183')/*确认收款*/
            : messages('common.detail')/*详情*/}
        </a>
      )
    },
    loanBillManagement: {
      title: messages('common.operation')/*操作*/, dataIndex: 'operator',
      render: (value, record) => <div>
        {
          record.stayWriteOffAmount > 0 && !record.creditLocked &&
          this.props.options.repaymentOption.option5 === 'true'
          && <div>
            <a
              onClick={e => this.handleRepayment(e,record)}
              disabled={this.props.currentPageRoute.subFunctions.find(item =>
                item.key === 'loan-global-view').operationType === 'R'}
            >
              {messages('finance-1.key85')/*新建还款*/}
            </a>
          </div>
        }
        {
          record.stayWriteOffAmount > 0 && (
            (record.payeeType === 1001 && ~[1005, 1006].indexOf(record.status)) ||
            (record.payeeType === 1002 && ~[1005, 1006, 1008].indexOf(record.status))
          ) &&
          this.props.options.repaymentOption.option12 === 'true' && (
            <div>
              <a
                onClick={e => this.handleTurn(e,record)}
                disabled={this.props.currentPageRoute.subFunctions.find(item =>
                  item.key === 'loan-global-view').operationType === 'R'}
              >
                {messages('finance-1.key472')/*转交*/}
              </a>
            </div>
          )
        }
        <a onClick={e => this.handleViewHistory(e, record)}>{messages('finance-1.key86')/*还款历史*/}</a>
      </div>
    }
  };

  handleTurn = (e, record) => {
    e.stopPropagation();
    ListSelector.open({
      type: 'user',
      extraParams: {
        setOfBooksId: record.setOfBooksId
      },
      single: true
    }, this).then(itemList => {
      const { fullName, id } = itemList[0];
      Modal.confirm({
        title: messages('finance-1.key473',{arg1: fullName})/*转交后，该笔借款可由还款人“{arg1}”操作还款、报销。*/,
        onOk: () => {
          this.setState({ tableLoading: true });
          loanAndRefundService.transfer({ payeeId: id, loanLineId: record.id }).then(() => {
            message.success(messages('common.operate.success')/*操作成功*/);
            this.setState({ tableLoading: false }, this.tabRef.getList);
          }).catch(e => {
            this.setState({ tableLoading: false });
            message.error(e.response.data.message);
          })
        }
      })
    })
  };

  handleRepayment = (e, record) => {
    e.stopPropagation();
    this.setState({ editRecord: record });
  };

  turnToRepay = info => {
    SlideFrame.open({
      content: repaymentContent,
      params: { info, loanRefund: true },
      title: messages('finance-1.key85')/*新建还款*/,
      afterClose: value => {
        this.setState({ editRecord: {} });
        value &&  this.content.tabRef.getList();
      }
    }, this);
  };

  render() {
    const { nowStatus, historyModal, historyId, editRecord } = this.state;
    const { subFunctions } = this.props.currentPageRoute;
    return (
      <div>
        <Template>
          <Header>
            <Tabs defaultActiveKey={nowStatus} onChange={this.onChangeTabs}>
              {
                subFunctions.map(item => item.operationType !== 'H' && <Tabs.TabPane tab={item.resourceName} key={getCamelCase(item.key)}/>)
              }
            </Tabs>
          </Header>
          <Middle>
            <TemplateContent
              tableKey={nowStatus}
              operate={this.operate[nowStatus]}
              onRef={content => this.content = content}
            />
          </Middle>
        </Template>
        <ViewHistory
          visible={historyModal}
          id={historyId}
          handleViewRefund={this.handleViewRefund}
          close={() => this.setState({ historyModal: false })}
        />
        <TransactionModal
          record={editRecord}
          onOK={this.turnToRepay}
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    options: state.login.options,
    currentPageRoute: state.main.currentPageRoute
  }
}

export default LoanRefund
